﻿using System;
using System.Linq;
using System.Windows;
using Coevery.ViewModel.EntityDataService;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
using Coevery.ViewModel;
using Microsoft.Phone.Shell;
using System.Windows.Controls.Primitives;
using Microsoft.Phone.Tasks;

namespace Coevery.PhoneApp
{
    public partial class LeadDetail : PhoneApplicationPage
    {
        private string _leadId;
        private Popup _popup;
        private LeadViewModel _leadViewModel;

        public LeadDetail()
        {
            InitializeComponent();
            _leadViewModel = new LeadViewModel();
            _leadViewModel.EnableButton += SetApplicationBarIconButtonEnabled;
            _leadViewModel.Popup = _popup = new Popup { Child = new PopuWait() };
            DataContext = _leadViewModel;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            if (e.NavigationMode != NavigationMode.Back)
            {
                _leadId = string.Empty;
                if (NavigationContext.QueryString.TryGetValue("Lead", out _leadId))
                {
                    _leadViewModel.LeadId = new Guid(_leadId);
                    _leadViewModel.LoadData();
                }
            }
        }

        private void AddComments_Click(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/Comment.xaml?Action=Add&ObjectType=Lead&ObjectId=" + _leadId, UriKind.Relative));
        }

        private void EditLeadComment_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = (MenuItem)sender;
            var note = (Note)menuItem.DataContext;
            PhoneApplicationService.Current.State["Note"] = note;

            NavigationService.Navigate(
                new Uri("/Comment.xaml?Action=Edit&ObjectType=Lead&ObjectId=" + _leadId, UriKind.Relative));
        }

        private void DeleteLeadComment_Click(object sender, RoutedEventArgs e)
        {
            var menuItem = (MenuItem)sender;
            var note = (Note)menuItem.DataContext;
            note.IsDeleted = true;
            BaseViewModel.Context.UpdateObject(note);
            BaseViewModel.Context.BeginSaveChanges(OnNodeDeleted, BaseViewModel.Context);
        }

        private void OnNodeDeleted(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() => {
                _popup.IsOpen = true;
                SetApplicationBarIconButtonEnabled(false, null);
                BaseViewModel.Context.EndSaveChanges(result);
                _leadViewModel.LoadData();
            });
        }

        private void Refresh_Click  (object sender, EventArgs e)
        {
            var selectedPivotItem = ctlPanorama.SelectedItem as PivotItem;
            if (selectedPivotItem.Name == "PanDetail")
            {
                _leadViewModel.LoadData();
            }

            if (selectedPivotItem.Name == "PanComments")
            {
                _leadViewModel.LoadData();
            }
        }

        public void SetApplicationBarIconButtonEnabled(object sender, EventArgs e)
        {
            foreach (ApplicationBarIconButton item in ApplicationBar.Buttons)
            {
                item.IsEnabled = ((bool?)sender) ?? false;
            }
        }

        private void MobilePhone_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var phone = CurrentLead.MobilePhone;
            if (!string.IsNullOrEmpty(phone))
            {
                var task = new PhoneCallTask {PhoneNumber = phone};
                task.Show();
            }
        }

        private void Email_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var emailAddress = CurrentLead.EmailAddress;
            if (!string.IsNullOrEmpty(emailAddress))
            {
                var task = new EmailComposeTask {To = emailAddress};
                task.Show();
            }
        }

        private void WebSiteUrl_Hold(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var webSiteUrl = CurrentLead.WebSiteUrl;
            if (!string.IsNullOrEmpty(webSiteUrl))
            {
                var task = new WebBrowserTask {Uri = new Uri(webSiteUrl)};
                task.Show();
            }
        }

        private void Home_Click(object sender, EventArgs e)
        {
            this.NavigationService.GoBack();
        }

        private Lead CurrentLead { get { return _leadViewModel.Leads.First(); } }

        private void ApplicationBarMenuItem_Click(object sender, EventArgs e)
        {
            var statusCode = 1;
            var status = "new";
            var menuItem = sender as ApplicationBarMenuItem;

            switch (menuItem.Text)
            {
                case "Convert to assigned":
                    statusCode = 2;
                    status = "assigned";
                    break;
                case "Convert to in process":
                    statusCode = 3;
                    status = "in process";
                    break;
                case "Convert to recycled":
                    statusCode = 5;
                    status = "recycled";
                    break;
                case "Convert to dead":
                    statusCode = 6;
                    status = "dead";
                    break;
            }

            var result = MessageBox.Show("Are you sure you want to convert the status to " + status + "?", "Information", MessageBoxButton.OKCancel);
            if(result == MessageBoxResult.OK)
            {
                var currentLead = _leadViewModel.Leads[0];
                currentLead.StatusCode = statusCode;
                BaseViewModel.Context.UpdateObject(currentLead);
                BaseViewModel.Context.BeginSaveChanges(OnChangesSaved, BaseViewModel.Context);
            }
        }

        private void OnChangesSaved(IAsyncResult result)
        {
            Dispatcher.BeginInvoke(() => BaseViewModel.Context.EndSaveChanges(result));
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (_popup.IsOpen == true)
            {
                _popup.IsOpen = false;
            }
        }
    }
}